<template>
  <el-dialog
    class="flow-dialog"
    title="角色"
    :model-value="visible"
    width="30%"
    destroy-on-close
    center
    modal
    :close-on-click-modal="false"
    :show-close="false"
  >
    <el-form
      ref="formRef"
      :model="roleForm"
      :rules="rules"
      inline-message
      :status-icon="true"
      label-width="80"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model="roleForm.name"
          placeholder="请输入角色名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="角色代码" prop="code">
        <el-input
          v-model="roleForm.code"
          placeholder="请输入角色代码"
          clearable
        />
      </el-form-item>
      <el-form-item label="角色说明" prop="description">
        <el-input
          v-model="roleForm.description"
          placeholder="请输入角色说明"
          type="textarea"
          :rows="2"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          :icon="useRenderIcon('material-symbols:check')"
          @click="submit()"
        >
          保存
        </el-button>
        <el-button
          type="danger"
          :loading="loading"
          :icon="useRenderIcon('material-symbols:close')"
          @click="close()"
        >
          关闭
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { FormInstance } from "element-plus";
import { Role } from "@/api/model/roleModel";
import { defineComponent, reactive, ref } from "vue";
import { checkCode, saveRole } from "@/api/role";
import { message } from "@/utils/message";

const loading = ref(false);
const visible = ref(false);
const add = ref(true);
const formRef = ref<FormInstance>();
const roleForm = ref<Role>({});

const validCode = async (rule, value, callback) => {
  if (value == null || value === "") {
    callback(new Error("请输入角色代码"));
  } else {
    if (!/\w{4,50}/.test(value)) {
      callback(
        new Error(
          "角色代码只能使用英文，数字和下划线 _ ，且必须在4到50个字符之间"
        )
      );
    } else {
      let usable;
      if (add.value) {
        usable = await checkCode(value);
      } else {
        usable = await checkCode(value, roleForm.value.id);
      }
      if (!usable) {
        callback(new Error("角色代码已被使用"));
      }
    }
  }
  callback();
};

const rules = reactive({
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    {
      min: 2,
      max: 20,
      message: "角色名称必须在2-20个字符之间",
      trigger: "blur",
    },
  ],
  code: [
    { required: true, message: "请输入角色代码", trigger: "blur" },
    { validator: validCode, trigger: "blur" },
  ],
  description: [
    {
      max: 200,
      message: "角色说明必须在200个字符以内",
      trigger: "blur",
    },
  ],
});

const close = () => {
  visible.value = false;
};
const openAdd = () => {
  roleForm.value = {
    state: true,
  };
  add.value = true;
  visible.value = true;
};
const openEdit = (form: Role) => {
  roleForm.value = {
    id: form.id,
    code: form.code,
    name: form.name,
    state: form.state,
    description: form.description,
  } as Role;
  add.value = false;
  visible.value = true;
};

export default defineComponent({
  setup(props, context) {
    function reloadList() {
      context.emit("reload");
    }
    function submit() {
      formRef.value.validate(valid => {
        if (valid) {
          loading.value = true;
          saveRole(roleForm.value)
            .then(res => {
              if (res) {
                message("保存成功", { type: "success" });
                reloadList();
                close();
              } else {
                message("保存失败", { type: "error" });
              }
            })
            .catch(e => {
              message(e.message, { type: "error" });
            })
            .finally(() => {
              loading.value = false;
            });
        }
      });
    }
    return {
      formRef,
      rules,
      loading,
      visible,
      add,
      roleForm,
      close,
      submit,
      useRenderIcon,
    };
  },
});

export function initRoleDialog() {
  return {
    openAdd,
    openEdit,
  };
}
</script>
<style scoped></style>
